import { Injectable } from '@nestjs/common';
import { errorText } from 'src/utils';
import * as winston from 'winston';
import * as DailyRotateFile from 'winston-daily-rotate-file';

@Injectable()
export class LoggerService {
  private logger = null;
  constructor() {
    this.logger = winston.createLogger({
      level: process.env.NODE_ENV != 'production' ? 'silly' : 'info',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
        winston.format.colorize(),
        winston.format.printf(({ level, message, timestamp }) => {
          return `[${timestamp}][${level}] ${message}`;
        })
      ),
      transports: [
        // 输出到控制台上
        process.env.NODE_ENV != 'production' ? new winston.transports.Console() : null,
        new DailyRotateFile({
          filename: 'logs/error-%DATE%.log',
          zippedArchive: true,
          maxSize: '20m',
          maxFiles: '14d',
          level: 'error',
        }),
        new DailyRotateFile({
          filename: 'logs/info-%DATE%.log',
          datePattern: 'YYYY-MM-DD-HH',
          zippedArchive: true,
          maxSize: '20m',
          maxFiles: '14d',
          level: 'info',
        }),
      ],
    });
  }

  // log level 0
  public error(err: unknown, ...metadata: unknown[]): void {
    const message = errorText(err);
    this.logger.error(message, ...metadata);
  }

  // log level 1
  public warn(message: string, ...metadata: unknown[]): void {
    this.logger.warn(message, ...metadata);
  }

  // log level 2
  public info(message: string, ...metadata: unknown[]): void {
    this.logger.info(message, ...metadata);
  }

  // log level 3
  public http(message: string, ...metadata: unknown[]): void {
    this.logger.http(message, ...metadata);
  }

  // log level 4
  public verbose(message: string, ...metadata: unknown[]): void {
    this.logger.verbose(message, ...metadata);
  }

  // log level 5
  public debug(message: string, ...metadata: unknown[]): void {
    this.logger.debug(message, ...metadata);
  }

  // log level 6
  public silly(message: string, ...metadata: unknown[]): void {
    this.logger.silly(message, ...metadata);
  }
}
